﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using webRuntimeComponent;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.System;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The User Control item template is documented at http://go.microsoft.com/fwlink/?LinkId=234236

namespace SplitViewOptions.BusinessControl
{
    public sealed partial class MyUserControl1 : UserControl
    {
        public MyUserControl1()
        {
            this.InitializeComponent();
            Webview.Navigate(new Uri("http://m.baidu.com/", UriKind.RelativeOrAbsolute));
            App.Secondwebview = Webview;
            Webview.NewWindowRequested += homewebview_NewWindowRequested;
            Webview.PermissionRequested += Homewebview_PermissionRequested;
            Webview.UnsupportedUriSchemeIdentified += Homewebview_UnsupportedUriSchemeIdentified;
            Webview.DOMContentLoaded += Homewebview_DOMContentLoaded;
            Webview.FrameContentLoading += Homewebview_FrameContentLoading;
            Webview.FrameDOMContentLoaded += Homewebview_FrameDOMContentLoaded;
        }

        private Grid _menugrid;
        public MyUserControl1(Grid menugrid)
        {
            _menugrid = menugrid;

            this.InitializeComponent();
            WebViewSettings wbsetting = Webview.Settings;
            // homewebview.AllowedScriptNotifyUris.Add(App.currenturl);        
            wbsetting.IsJavaScriptEnabled = true;
            wbsetting.IsIndexedDBEnabled = true;
            Webview.Navigate(new Uri("http://m.baidu.com/", UriKind.RelativeOrAbsolute));
            App.Secondwebview = Webview;
            Webview.NewWindowRequested += homewebview_NewWindowRequested;
            Webview.PermissionRequested += Homewebview_PermissionRequested;
            Webview.UnsupportedUriSchemeIdentified += Homewebview_UnsupportedUriSchemeIdentified;
            Webview.DOMContentLoaded += Homewebview_DOMContentLoaded;
            Webview.FrameContentLoading += Homewebview_FrameContentLoading;
            Webview.FrameDOMContentLoaded += Homewebview_FrameDOMContentLoaded;
        }
        private async void Homewebview_FrameDOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
        {
            Debug.WriteLine("Homewebview_FrameDOMContentLoaded");
            //  localprogressinfo.Update(0.7, "FrameDOMContentLoaded");
            try
            {
                // WebView native object must be inserted in the OnNavigationStarting event handler
                KeyHandler winRtObject = new KeyHandler();
                // Expose the native WinRT object on the page's global object
                Webview.AddWebAllowedObject("NotifyApp", winRtObject);
                //   winRTObject.DoWork += WinRTObject_DoWork;
                winRtObject.NumberChanged += WinRTObject_NumberChanged;
                // inject event handler to arbitrary page once the DOM is loaded
                //  "document.getElementById(\"hnmain\").addEventListener(\"click\", function () { NotifyApp.setKeyCombination(43); }); " 
                //string strr = "function SayHelloWorld(me) {    var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {   imgboxes[i].onclick = function(){  NotifyApp.setKeyCombination(this.src);  }; } }";

                //string tevalstr = "   var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {    imgboxes[i].onclick = function(){  NotifyApp.setKeyCombination(this.src);  }; } ";

                //var ateval = await homewebview.InvokeScriptAsync("eval", new[] { tevalstr });
                string evalstr = "   var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {    imgboxes[i].onmousedown = function(){ NotifyApp.setKeyCombination(this.src);  }; } ";

                var imgeval = await Webview.InvokeScriptAsync("eval",
                new[] { evalstr });
                //  string ataghref = "   var atag = document.getElementsByTagName(\"a\");   for (var i = 0; i < atag.length; i++) {    atag[i].onclick = function(){  NotifyApp.setKeyCombination(this.href);  }; } ";
                //  var aeval = await homewebview.InvokeScriptAsync("eval",
                //new[] { ataghref });
                string videotaghref = "   var videotag = document.getElementsByTagName(\"video\");   for (var i = 0; i < videotag.length; i++) {    videotag[i].onclick = function(){  NotifyApp.setKeyCombination(this.src);  }; } ";
                var videoeval = await Webview.InvokeScriptAsync("eval",
                new[] { videotaghref });

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

            // localprogressinfo.Opacity = 0.5;
        }
        private void WinRTObject_NumberChanged(object sender, TextChangeEventArgs e)
        {
            string url = e.Message;
            Debug.WriteLine(url);
            Parseurl(url);
        }
        private void Parseurl(string url)
        {
            _menugrid.Visibility = Visibility.Visible;
            Grid picstackpanel = _menugrid.FindName("picstackpanel") as Grid;
            if (picstackpanel != null)
            {
                picstackpanel.Visibility = Visibility.Visible;
                Button picsavebtn = _menugrid.FindName("picsavebtn") as Button;
                Button picsavetolibrarybtn = _menugrid.FindName("picsavetolibrarybtn") as Button;
                Button savevideo = _menugrid.FindName("savevideo") as Button;
                string Text = url;
                SolidColorBrush tem = new SolidColorBrush
                (Color.FromArgb(255, Convert.ToByte(_ran.Next(0, 255)),
                    Convert.ToByte(_ran.Next(0, 255)),
                    Convert.ToByte(_ran.Next(0, 255))));
                if (Text.Contains(".jpeg") || Text.Contains(".gif") || Text.Contains(".jpg") || Text.Contains(".png") || Text.Contains(".1jpg") || Text.EndsWith(".1png"))
                {

                    picstackpanel.Visibility = Visibility.Visible;
                    if (picsavebtn != null)
                    {
                        picsavebtn.Tag = Text;


                        picsavebtn.Foreground = tem;
                    }
                    if (picsavetolibrarybtn != null)
                    {
                        picsavetolibrarybtn.Foreground = tem;
                        picsavetolibrarybtn.Tag = Text;
                    }
                }
                if (Text.StartsWith("http"))
                {
                    if (Text.Contains(".mp4") || Text.Contains(".3gp"))
                    {
                        picstackpanel.Visibility = Visibility.Visible;
                        if (savevideo != null)
                        {
                            savevideo.Tag = Text;
                            savevideo.Foreground = tem;
                        }
                    }
                    else
                    {
                        picstackpanel.Visibility = Visibility.Visible;
                        if (picsavebtn != null)
                        {
                            picsavebtn.Tag = Text;


                            picsavebtn.Foreground = tem;
                        }
                        if (picsavetolibrarybtn != null)
                        {
                            picsavetolibrarybtn.Foreground = tem;
                            picsavetolibrarybtn.Tag = Text;
                        }
                    }
                }
                picstackpanel.Visibility = Visibility.Visible;
            }
        }
        private Random _ran = new Random();
        private void Homewebview_FrameContentLoading(WebView sender, WebViewContentLoadingEventArgs args)
        {
            Debug.WriteLine("Homewebview_FrameContentLoading");
            //localprogressinfo.Update(0.6, "FrameDOMContentLoaded");
            //localprogressinfo.Opacity = 1;
        }
        private async void Homewebview_DOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
        {
            Debug.WriteLine("Homewebview_DOMContentLoaded");
            //localprogressinfo.Update(0.7, "FrameDOMContentLoaded");
            //localprogressinfo.Opacity = 1;
            try
            {
                // WebView native object must be inserted in the OnNavigationStarting event handler
                KeyHandler winRtObject = new KeyHandler();
                // Expose the native WinRT object on the page's global object
                Webview.AddWebAllowedObject("NotifyApp", winRtObject);
                //   winRTObject.DoWork += WinRTObject_DoWork;
                winRtObject.NumberChanged += WinRTObject_NumberChanged;
                // inject event handler to arbitrary page once the DOM is loaded
                //  "document.getElementById(\"hnmain\").addEventListener(\"click\", function () { NotifyApp.setKeyCombination(43); }); " 
                //string strr = "function SayHelloWorld(me) {    var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {   imgboxes[i].onclick = function(){  NotifyApp.setKeyCombination(this.src);  }; } }";

                //string tevalstr = "   var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {    imgboxes[i].onclick = function(){  NotifyApp.setKeyCombination(this.src);  }; } ";

                //var ateval = await homewebview.InvokeScriptAsync("eval", new[] { tevalstr });
                string evalstr = "   var imgboxes = document.getElementsByTagName(\"img\");   for (var i = 0; i < imgboxes.length; i++) {    imgboxes[i].onmousedown = function(){ NotifyApp.setKeyCombination(this.src);  }; } ";

                var imgeval = await Webview.InvokeScriptAsync("eval",
                new[] { evalstr });
                //  string ataghref = "   var atag = document.getElementsByTagName(\"a\");   for (var i = 0; i < atag.length; i++) {    atag[i].onclick = function(){  NotifyApp.setKeyCombination(this.href);  }; } ";
                //  var aeval = await homewebview.InvokeScriptAsync("eval",
                //new[] { ataghref });
                string videotaghref = "   var videotag = document.getElementsByTagName(\"video\");   for (var i = 0; i < videotag.length; i++) {    videotag[i].onclick = function(){  NotifyApp.setKeyCombination(this.src);  }; } ";
                var videoeval = await Webview.InvokeScriptAsync("eval",
                new[] { videotaghref });

            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }

        }
        private void homewebview_NewWindowRequested(WebView sender, WebViewNewWindowRequestedEventArgs args)
        {

            if (App.Ismobile)
            {
                App.Navigatemobilemode(Webview, args.Uri);
            }
            else
            {
                Webview.Navigate(args.Uri);
            }
            args.Handled = true;
        }

        private void Homewebview_UnsupportedUriSchemeIdentified(WebView sender, WebViewUnsupportedUriSchemeIdentifiedEventArgs args)
        {

            Debug.WriteLine("Homewebview_UnsupportedUriSchemeIdentified");
            args.Handled = true;

        }
        private void Homewebview_PermissionRequested(WebView sender, WebViewPermissionRequestedEventArgs args)
        {
            Debug.WriteLine("Homewebview_PermissionRequested");
            if (args.PermissionRequest.PermissionType == WebViewPermissionType.Geolocation)
            {
                args.PermissionRequest.Allow();
            }
        }
        private ObservableCollection<string> _suggestions = new ObservableCollection<string>();
        private void AutoSuggestBox_TextChanged(AutoSuggestBox sender, AutoSuggestBoxTextChangedEventArgs args)
        {
            _suggestions.Clear();
            string str = sender.Text;
            if (str.StartsWith("http") || str.StartsWith("www"))
            {

            }
            else
            {
                _suggestions.Add("http://www." + sender.Text + ".com");
                _suggestions.Add("http://www." + sender.Text + ".cn");
                _suggestions.Add("http://www." + sender.Text + ".net");
                _suggestions.Add("http://www." + sender.Text + ".com.cn");
                _suggestions.Add("http://www." + sender.Text + ".info");
                _suggestions.Add("http://www." + sender.Text + ".me");
                _suggestions.Add("http://wap." + sender.Text + ".com");
                _suggestions.Add("http://wap." + sender.Text + ".cn");
                _suggestions.Add("http://m." + sender.Text + ".cn");
                //suggestions.Add("搜索:" + sender.Text );
                //suggestions.Add("搜图片:" + sender.Text);
                //suggestions.Add("搜视频:" + sender.Text);
                sender.ItemsSource = _suggestions;
            }
            Flyout f = this.searchbtn.Flyout as Flyout;
            if (f != null)
            {
                //f.ShowAt(autoSuggestBox);
            }
        }
        private void AutoSuggestBox_QuerySubmitted(AutoSuggestBox sender, AutoSuggestBoxQuerySubmittedEventArgs args)
        {
            if (args.ChosenSuggestion != null)
            {
                string sargsstr = args.ChosenSuggestion.ToString();
                if (sargsstr.StartsWith("http"))
                {
                }
                else if (sargsstr.StartsWith("搜索"))
                {

                    string url = "https://www.baidu.com/s?wd=" + sargsstr.Split(':')[1];

                }
                else if (sargsstr.StartsWith("搜图片"))
                {
                    string url = "http://image.baidu.com/search/index?tn=baiduimage&word=" + sargsstr.Split(':')[1];

                }
                else if (sargsstr.StartsWith("搜视频"))
                {
                    string url = "http://www.soku.com/search_video/q_" + sargsstr.Split(':')[1];

                }
                else
                {
                }
                App.Currenturl = new Uri(sargsstr, UriKind.RelativeOrAbsolute);
                //loadwebsitehtml();
                //  MainFrame.Navigate(typeof(HomePage));
            }
            else
            {

            }
        }
        private void picbtn_Click(object sender, RoutedEventArgs e)
        {
            string word = autoSuggestBox.Text;
            Flyout flyout = this.moresearch.Flyout as Flyout;
            flyout?.Hide();
            string str;
            string buttonStr = (sender as Button)?.Content?.ToString();
            if (App.Ismobile)
            {
                switch (buttonStr)
                {
                    case "图片":
                        str = "http://image.baidu.com/search/index?tn=baiduimage&word=" + word;
                        break;
                    case "搜狗":
                        str = "http://www.sogou.com/web?query=" + word;
                        break;
                    case "360":
                        str = "http://www.haosou.com/s?q=" + word;
                        break;
                    case "bing":
                        str = "http://global.bing.com/search?q=" + word;
                        break;
                    case "bing中国":
                        str = "http://cn.bing.com/search?q=" + word;
                        break;
                    case "google":
                        str = "https://www.google.com/#&q=" + word;
                        break;
                    case "google中国":
                        str = "https://www.google.com.hk/#&q=" + word;
                        break;
                    case "视频":
                        str = "http://v.baidu.com/v?ct=301989888&s=25&word=" + word;
                        break;
                    case "地图":
                        str = "http://map.baidu.com/";
                        break;
                    case "百科":
                        str = "http://baike.baidu.com/search/word?word=" + word;
                        break;
                    case "贴吧":
                        str = "http://tieba.baidu.com/f?ie=utf-8&fr=bks0000&kw=" + word;
                        break;
                    case "知道":
                        str = "http://zhidao.baidu.com/search?ct=17&pn=0&tn=ikaslist&rn=10&word=" + word;
                        break;
                    case "文库":
                        str = "http://wenku.baidu.com/search?word=" + word;
                        break;
                    case "pic":
                        str = "ttps://www.google.com/search?newwindow=1&hl=en&site=imghp&tbm=isch&q=" + word;
                        break;
                    case "video":
                        str = "https://www.youtube.com/results?search_query=" + word;
                        break;
                    case "map":
                        str = "https://www.google.com/maps/search/" + word;
                        break;
                    default:
                        str = "https://www.google.com/";
                        break;
                }
            }
            else
            {
                switch (buttonStr)
                {
                    case "图片":
                        str = "http://image.baidu.com/search/index?tn=baiduimage&word=" + word;
                        break;
                    case "视频":
                        str = "http://v.baidu.com/v?ct=301989888&s=25&word=" + word;
                        break;
                    case "地图":
                        str = "http://map.baidu.com/";
                        break;
                    case "百科":
                        str = "http://baike.baidu.com/search/word?word=" + word;
                        break;
                    case "贴吧":
                        str = "http://tieba.baidu.com/f?ie=utf-8&fr=bks0000&kw=" + word;
                        break;
                    case "知道":
                        str = "http://zhidao.baidu.com/search?ct=17&pn=0&tn=ikaslist&rn=10&word=" + word;
                        break;
                    case "文库":
                        str = "http://wenku.baidu.com/search?word=" + word;
                        break;
                    case "搜狗":
                        str = "http://www.sogou.com/web?query=" + word;
                        break;
                    case "360搜":
                        str = "http://www.haosou.com/s?q=" + word;
                        break;
                    case "bing":
                        str = "http://global.bing.com/search?q=" + word;
                        break;
                    case "bing中国":
                        str = "http://cn.bing.com/search?q=" + word;
                        break;
                    case "google":
                        str = "https://www.google.com/#&q=" + word;
                        break;
                    case "google中国":
                        str = "https://www.google.com.hk/#&q=" + word;
                        break;
                    case "video":
                        str = "https://www.youtube.com/results?search_query=" + word;
                        break;
                    case "map":
                        str = "https://www.google.com/maps/search/" + word;
                        break;
                    default:
                        str = "https://www.google.com/";
                        break;
                }
            }
            App.Currenturl = new Uri(str, UriKind.RelativeOrAbsolute);
            //loadwebsitehtml();
        }
        private void searchbtn_Click(object sender, RoutedEventArgs e)
        {
            root.Visibility = Visibility.Collapsed;
            // MySplitView.IsPaneOpen = false;
            string text = autoSuggestBox.Text;
            if (string.IsNullOrEmpty(text))
            {
                string urlBiadu = "https://m.baidu.com";

                App.Currenturl = new Uri(urlBiadu, UriKind.RelativeOrAbsolute);

            }
            else
            {
                string url = "http://www.baidu.com/s?wd=" + text;
                App.Currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
            }

            Webview.Navigate(App.Currenturl);

            // MainFrame.Navigate(typeof(HomePage));
            //  homewebview.Navigate(new Uri(url, UriKind.RelativeOrAbsolute));
            //   loadwebsitehtml();
        }
        private void autoSuggestBox_KeyDown(object sender, Windows.UI.Xaml.Input.KeyRoutedEventArgs e)
        {
            if (e.Key == VirtualKey.Enter || e.Key == VirtualKey.Accept || e.Key == Windows.System.VirtualKey.Execute)
            {
                if (autoSuggestBox.Text.StartsWith("http") || autoSuggestBox.Text.StartsWith("www"))
                {
                    //   Uri oneuri = new Uri(str, UriKind.RelativeOrAbsolute);

                    App.Currenturl = new Uri(autoSuggestBox.Text, UriKind.RelativeOrAbsolute);
                    // MainFrame.Navigate(typeof(HomePage));
                    //loadwebsitehtml();
                }
                else if (false)
                {

                }
                else
                {
                    string text = autoSuggestBox.Text;
                    string url = "http://www.baidu.com/s?wd=" + text;

                    App.Currenturl = new Uri(url, UriKind.RelativeOrAbsolute);
                    //MainFrame.Navigate(typeof(HomePage));
                    //  loadwebsitehtml();
                }
            }
            Webview.Navigate(App.Currenturl);
        }

        private void UserControl_Unloaded(object sender, RoutedEventArgs e)
        {
            App.Secondwebview = null;
        }

        private void Grid_ManipulationCompleted(object sender, ManipulationCompletedRoutedEventArgs e)
        {
            App.Issecondwebviewmanipulated = true;
        }

        private void UserControl_Holding(object sender, HoldingRoutedEventArgs e)
        {

        }
    }
}
